import React, {Children, Component, cloneElement} from 'react'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import {actions} from '../actions'
import Main from '../components/Main'
import Footer from '../components/Footer'
import Loading from '../components/Loading'
import Message from '../components/Message'

@connect(
  state => ({state: state.common}),
  dispatch => ({
    ...bindActionCreators({
      pageLoading: actions.pageLoading,
      fetchAddToCart: actions.fetchAddToCart,
      hideMessage: actions.hideMessage,
      showMessage: actions.showMessage,
      setLoginToken: actions.setLoginToken,
      loginAuth: actions.loginAuth,
      hideFooter: actions.hideFooter,
      fetchWechatConfig: actions.fetchWechatConfig,
      fetchWechatShare: actions.fetchWechatShare,
      fetchCartCount: actions.fetchCartCount
    }, dispatch)
  })
)

export default class Layout extends Component {
  constructor() {
    super()
  }

  componentWillMount() {
    let url = `${location.protocol}//${location.host}${location.pathname}${location.search}`

    sessionStorage.setItem('categoryId', null)

    if (process.env.NODE_ENV === 'development') {
      const {state: {token}, setLoginToken} = this.props

      if (!token) {
        sessionStorage.setItem('token', 'eyJhbGciOiJIUzI1NiJ9.eyJyYW5kb20iOjgzNDQxLCJ1c2VySWQiOiIxIn0.vlL_VZhnL_rm5yDA4sAnwbM3zLCol3I9a3ZJKVCC3BM')
        let token = sessionStorage.getItem('token')
        setLoginToken(token, false)
        this.props.fetchCartCount()
        this.props.fetchWechatConfig({url}).then(() => {
          this.props.fetchWechatShare()
        })
      } else {
        this.props.fetchCartCount()
        this.props.fetchWechatConfig({url}).then(() => {
          this.props.fetchWechatShare()
        })
      }
    } else {
      const {loginAuth} = this.props

      loginAuth().then(() => {
        if (sessionStorage.getItem('token')) {
          this.props.fetchCartCount()
          this.props.fetchWechatConfig({url}).then(() => {
            this.props.fetchWechatShare()
          })
        }
      })
    }
  }

  componentDidMount() {
    let startY, endY

    document.body.ontouchstart = function(e) {
      startY = e.touches[0].clientY
    }

    document.body.ontouchmove = function(e) {
      endY = e.touches[0].clientY

      let el = document.querySelector('.J-scroll'),
        scrollTop = el ? el.scrollTop : null,
        offsetHeight = el ? el.offsetHeight : null,
        scrollHeight = el ? el.scrollHeight : null

      // If (endY > startY && scrollTop == 0) {
      //   E.preventDefault()
      // }

      // If (endY < startY && scrollTop + offsetHeight >= scrollHeight) {
      //   E.preventDefault()
      // }
    }
  }

  _savePosition = (page, selector) => {
    let name = `${page}Position`,
      el = document.querySelector(selector)

    el && sessionStorage.setItem(name, el.scrollTop)
  }

  _loadPosition = (page, selector) => {
    let name = `${page}Position`,
      el = document.querySelector(selector)

    if (!el) {
      return
    }

    el.scrollTop = parseInt(sessionStorage.getItem(name))
  }

  // 正则匹配emoji并替换为空串
  _emojiReplace = org => {
    let regStr = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig,
      value

    if (regStr.test(org)) {
      value = org.replace(regStr, '')

      return value
    } else {
      return org
    }
  }
  render() {
    const {state: {isLoading, token, isMask, ifMessage, ifEmptyStation, message, noFooter, cartCount}, children, pageLoading, fetchCartCount, fetchAddToCart, hideMessage, showMessage, hideFooter, fetchWechartShare, fetchWechatConfig, ...props} = this.props
    const savePosition = this._savePosition,
      loadPosition = this._loadPosition,
      emojiReplace = this._emojiReplace

    if (token) {
      return (
        <div style={{height: `${window.innerHeight}px`}}>
          <Main>
            {Children.map(children, child =>
                cloneElement(child, {fetchAddToCart, fetchCartCount, showMessage, hideFooter, fetchWechartShare, savePosition, loadPosition, emojiReplace, fetchWechatConfig, ...props})
            )}
          </Main>
          {!noFooter && <Footer cartCount={cartCount}/>}
          {(isLoading || isMask) && <Loading/>}
          {ifMessage && <Message message={message} hideMessage={hideMessage}/>}
            {ifEmptyStation && <EmptyStation message={message}/>}
        </div>
      )
    } else {
      return (
        <div style={{height: `${window.innerHeight}px`}}>
            {ifMessage && <Message message={message} hideMessage={hideMessage}/>}
        </div>
      )
    }
  }

}

// Style={{position: 'absolute', top: 0, bottom: 0, width: '100%', minHeight: '550px'}}
